<template>
  <div style="height: 100vh; display: flex; flex-direction: column; background: #f5f5f5;">
    <!-- 顶部导航栏 - 固定高度 -->
    <div style="height: 80px; background: white; border-bottom: 1px solid #ddd; display: flex; align-items: center; padding: 0 30px; flex-shrink: 0;">
      <a-button type="link" @click="goBack" style="padding: 0; margin-right: 20px; font-size: 16px;">
        <LeftOutlined />
        返回
      </a-button>
      <h1 style="color: #1890ff; margin: 0; font-size: 24px;">搜索结果</h1>
    </div>
    
    <!-- 主体内容 -->
    <div style="flex: 1; padding: 40px 20px;">
        <!-- 搜索框 -->
        <div style="background: white; padding: 30px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); margin-bottom: 30px; width: 100%;">
          <a-input-search
            v-model:value="searchQuery"
            placeholder="请输入案件名称、法条、关键词等..."
            enter-button="搜索"
            size="large"
            @search="onSearch"
          />
        </div>
        <!-- 搜索结果信息 -->
        <div v-if="searchQuery && !loading" style="background: white; padding: 16px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); margin-bottom: 20px;">
          <p style="margin: 0; color: #666;">
            搜索 "<strong style="color: #1890ff;">{{ searchQuery }}</strong>" 的结果，共找到 <strong>{{ pagination.total }}</strong> 条记录
          </p>
        </div>
        
        <!-- 文档类型筛选 -->
        <div v-if="searchQuery" style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); margin-bottom: 20px;">
          <div style="margin-bottom: 10px; font-weight: 600;">文档类型：</div>
          <a-radio-group v-model:value="docType" @change="onDocTypeChange" button-style="solid">
            <a-radio-button :value="null">全部</a-radio-button>
            <a-radio-button :value="0">法律</a-radio-button>
            <a-radio-button :value="1">案例</a-radio-button>
            <a-radio-button :value="2">判决书</a-radio-button>
            <a-radio-button :value="3">文章</a-radio-button>
          </a-radio-group>
        </div>
        
        <!-- 搜索结果 -->
        <a-spin :spinning="loading">
          <a-list
            :data-source="results"
            item-layout="vertical"
            size="large"
            :pagination="pagination"
            @change="onPageChange"
          >
            <template #renderItem="{ item }">
              <a-list-item style="background: white; margin-bottom: 16px; padding: 24px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
                <template #actions>
                  <span style="color: #999;">
                    <CalendarOutlined />
                    {{ item.publishDate }}
                  </span>
                  <span style="color: #999;">
                    来源：{{ item.source }}
                  </span>
                </template>
                
                <a-list-item-meta>
                  <template #title>
                    <div style="font-size: 18px; font-weight: 600; margin-bottom: 8px; cursor: pointer;" @click="viewDocument(item)" v-html="item.title"></div>
                  </template>
                  <template #description>
                    <div>
                      <div style="margin-bottom: 12px;">
                        <a-tag :color="getDocTypeColor(item.docType)">{{ getDocTypeText(item.docType) }}</a-tag>
                      </div>
                      <div style="color: #666; line-height: 1.6; margin-bottom: 12px;" v-html="item.content"></div>
                      <div v-if="item.keywords" style="color: #999; font-size: 14px;">
                        <strong>关键词：</strong><span v-html="item.keywords"></span>
                      </div>
                    </div>
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
            
            <template #empty>
              <div style="text-align: center; padding: 40px; color: #999;">
                <div style="font-size: 48px; margin-bottom: 16px;">📄</div>
                <p v-if="searchQuery">没有找到相关的文档</p>
                <p v-else>请输入关键词开始搜索</p>
              </div>
            </template>
          </a-list>
        </a-spin>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  CalendarOutlined,
  LeftOutlined
} from '@ant-design/icons-vue'
import { searchLegalDocument, addSearchHistory } from '@/api/search'

const route = useRoute()
const router = useRouter()

const searchQuery = ref('')
const results = ref([])
const loading = ref(false)
const docType = ref(null) // 文档类型筛选

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showQuickJumper: true,
  showSizeChanger: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 页面初始化
onMounted(() => {
  searchQuery.value = route.query.q || ''
  docType.value = route.query.docType ? parseInt(route.query.docType) : null
  if (searchQuery.value) {
    performSearch()
  }
})

// 搜索处理
const onSearch = async (value) => {
  if (!value || !value.trim()) {
    message.warning('请输入搜索关键词')
    return
  }
  
  searchQuery.value = value.trim()
  pagination.current = 1
  
  // 更新URL
  const query = { q: searchQuery.value }
  if (docType.value !== null) {
    query.docType = docType.value
  }
  router.push({ name: 'Search', query })
  
  // 添加搜索历史（如果用户已登录）
  const token = localStorage.getItem('token')
  if (token) {
    try {
      await addSearchHistory(searchQuery.value)
    } catch (error) {
      console.log('添加搜索历史失败:', error)
    }
  }
  
  // 执行搜索
  performSearch()
}

// 执行搜索
const performSearch = async () => {
  if (!searchQuery.value) return
  
  try {
    loading.value = true
    const params = {
      key: searchQuery.value,
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    }
    
    if (docType.value !== null) {
      params.docType = docType.value
    }
    
    const response = await searchLegalDocument(params)
    if (response.code === 200) {
      results.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      message.error(response.msg || '搜索失败')
      results.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('搜索出错:', error)
    message.error('搜索失败，请稍后重试')
    results.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 文档类型改变
const onDocTypeChange = () => {
  pagination.current = 1
  const query = { q: searchQuery.value }
  if (docType.value !== null) {
    query.docType = docType.value
  }
  router.push({ name: 'Search', query })
  performSearch()
}

// 分页改变
const onPageChange = (page, pageSize) => {
  pagination.current = page
  pagination.pageSize = pageSize
  performSearch()
}

// 获取文档类型颜色
const getDocTypeColor = (type) => {
  const colorMap = {
    0: 'blue',      // 法律
    1: 'green',     // 案例
    2: 'orange',    // 判决书
    3: 'purple'     // 文章
  }
  return colorMap[type] || 'default'
}

// 获取文档类型文本
const getDocTypeText = (type) => {
  const textMap = {
    0: '法律',
    1: '案例',
    2: '判决书',
    3: '文章'
  }
  return textMap[type] || '未知'
}

// 查看文档详情
const viewDocument = (item) => {
  // 所有文档都跳转到文档详情页
  router.push({ name: 'DocumentDetail', params: { id: item.id } })
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}
</script>

<style>
/* 搜索页面样式 */

.case-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.case-summary {
  color: #666;
  line-height: 1.5;
}

:deep(.ant-list-item-meta-title) {
  margin-bottom: 8px;
}

:deep(.ant-list-item-meta-title a) {
  color: #1890ff;
  font-size: 18px;
  font-weight: 600;
}

:deep(.ant-list-item-meta-title a:hover) {
  color: #40a9ff;
}

:deep(.ant-list-item-action) {
  margin-left: 0;
}

:deep(.ant-list-item-action > li) {
  padding: 0 8px;
  color: #999;
}
</style>
